package chapter8JVM_excute;

import java.lang.invoke.*;
import static java.lang.invoke.MethodHandles.lookup;
//演示invokedynamic的java代码 通过指定字符串作方法名进行方法的调用
public class P83_4 {
    public static void main(String[] args) throws Throwable {
        INDY_BootstrapMethod().invokeExact("dsadas");
    }

    public static void testMethod(String s){
        System.out.println("hello "+s);
    }
    public static CallSite bootstrapMethod(MethodHandles.Lookup lookup, String name, MethodType methodType) throws Throwable{
        return new ConstantCallSite(lookup.findStatic(P83_4.class,name,methodType));
    }
    public static MethodType MT_BootstrapMethodType()throws Throwable{
        //descriptor为类标识符的字符串示意 括号之间是类的参数类型（）括号外面是返回类型 最前面的L表示表示此对象类型。
        return MethodType.fromMethodDescriptorString("(Ljava/lang/invoke/MethodHandles$Lookup;" +
                "Ljava/lang/String;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;",null);
    }
    public static MethodHandle MH_BootstrapMethod()throws Throwable{
        return lookup().findStatic(P83_4.class,"bootstrapMethod",MT_BootstrapMethodType());
    }
    public static MethodHandle INDY_BootstrapMethod() throws Throwable{
        MethodType methodType = MethodType.methodType(void.class,String.class);
        MethodHandle methodHandle = MH_BootstrapMethod();
        CallSite cs = (CallSite) methodHandle.invokeWithArguments(lookup(),"testMethod",methodType);
        return cs.dynamicInvoker();
    }
}
